function arrToStr(arr) {
  let str = ''
  for (let i of arr) {
    str += i + ","
  }
  if (str.length > 0) {
    str = str.substr(0, str.length - 1);
  }
  return str
}

function countdown(t1, t2, tg) {
  /*
  t1 开始时 时间格式
  t2 结束时 时间格式
  tg 要获取的值 字符串
    d 天
    h 时
    m 分
    s 秒
  */
  //相差的毫秒数
  try {
    t1 = t1.replace(/-/g, "/")
  } catch (e) {}
  try {
    t2 = t2.replace(/-/g, "/")
  } catch (e) {}
  var ms = Date.parse(t1) - Date.parse(t2);
  var second = 1000;
  var minutes = 1000 * 60;
  var hours = minutes * 60;
  var days = hours * 24;
  var years = days * 365;
  //求出天数
  var d = prefixInteger(Math.floor(ms / days), 2);
  //求出除开天数，剩余的毫秒数
  ms %= days;
  var h = prefixInteger(Math.floor(ms / hours), 2);
  ms %= hours;
  var m = prefixInteger(Math.floor(ms / minutes), 2);
  ms %= minutes;
  var s = prefixInteger(Math.floor(ms / second), 2);
  ms %= second;
  var mi = prefixInteger(Math.floor(ms / 100), 2);
  //返回所需值并退出函数
  if (tg) {
    switch (tg) {
      case 'd':
        return d;
      case 'h':
        return h;
      case 'm':
        return m;
      case 's':
        return s;
    }
  } else {
    if (d - 0) {
      return `${d}天${h}:${m}:${s}`
    } else {
      return `${h}:${m}:${s}`
    }
  }
}
// 不足添0
function prefixInteger(num, length) {
  return (Array(length).join('0') + num).slice(-length)
}
// 格式化时间
function formatMsgTime(timespan, type) {
  timespan = timespan.replace(/-/g, '/')
  timespan = (new Date(timespan)).getTime()
  var dateTime = new Date(timespan)
  var year = dateTime.getFullYear()
  var month = prefixInteger(dateTime.getMonth() + 1, 2)
  var day = prefixInteger(dateTime.getDate(), 2)
  var hour = dateTime.getHours()
  var minute = dateTime.getMinutes()
  var seconds = dateTime.getSeconds()
  var now = new Date().getTime()
  var milliseconds = 0
  var timeSpanStr
  milliseconds = now - timespan
  var langType = 'zh-CN' || localStorage.langType
  if (!type && milliseconds < 0) {
    if (langType === 'zh-CN') {
      timeSpanStr = '未开始'
    } else {
      timeSpanStr = 'not started'
    }
  } else if (!type && milliseconds <= 1000 * 60 * 1) {
    if (langType === 'zh-CN') {
      timeSpanStr = '刚刚'
    } else {
      timeSpanStr = 'just recently'
    }
  } else if (!type && 1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
    if (langType === 'zh-CN') {
      timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'
    } else {
      timeSpanStr = Math.round((milliseconds / (1000 * 60))) + ' minutes ago'
    }
  } else if (!type && 1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
    if (langType === 'zh-CN') {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'
    } else {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + ' hours ago'
    }
  } else if (!type && 1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
    if (langType === 'zh-CN') {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'
    } else {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + ' days ago'
    }
  } else if (!type && milliseconds > 1000 * 60 * 60 * 24 * 15 && year === new Date().getFullYear()) {
    timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute
  } else {
    timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds
  }
  return timeSpanStr
}
// 手机号脱敏
function stringPhone(string, index = 4, num = 4) {
  console.log(string)
  if (!string) {
    return string
  }
  string = string.toString()
  string = string.split("");
  for (var i = index; i < index + num; i++) {
    string[i] = '*'
  }
  return string.join('')
}

function utf16to8(str) {
  var out, i, len, c
  out = ''
  len = str.length
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i)
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i)
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
    } else {
      out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
    }
  }
  return out
}
/*
 * obj 转 params字符串参数  
 * 例子：{a:1,b:2} => a=1&b=2
 */
function objParseParam(obj) {
  let paramsStr = "";
  if (obj instanceof Array) return paramsStr;
  if (!(obj instanceof Object)) return paramsStr;
  for (let key in obj) {
    paramsStr += `${key}=${obj[key]}&`;
  }
  return paramsStr.substring(0, paramsStr.length - 1);
}

/* 
 * obj 转 路由地址带参数
 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
 */
function objParseUrlAndParam(path, obj) {
  let url = path || "/";
  let paramsStr = "";
  if (obj instanceof Array) return url;
  if (!(obj instanceof Object)) return url;
  paramsStr = this.objParseParam(obj);
  paramsStr && (url += "?");
  url += paramsStr;
  return url;
}

/* 
 * 获取url字符串参数
 */
function getRequestParameters(locationhref) {
  let href = locationhref || "";
  let theRequest = new Object();
  let str = href.split("?")[1];
  if (str != undefined) {
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
    }
  }
  return theRequest;
}

function numberFoFixed2(val) {
  let splitNum = String(val).split('.')
  let decimal = splitNum[1]
  if (!Number(splitNum[0]) && splitNum.length > 1) {
    val = '0.' + decimal
  }
  if (decimal && decimal.length >= 2) {
    val = Number(val)
  }
  if (val) {
    if ((decimal && decimal.length) > 2) {
      val = Math.floor(val * 100) / 100
    } else {
      if (splitNum.length >= 2) {
        val = (splitNum[0] || 0) + '.' + splitNum[1]
      } else {
        val = Number(val)
      }
    }
  }
  return val
}

function loadJs(src) {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script')
    script.type = "text/javascript"
    script.onload = () => {
      resolve()
    }
    script.onerror = () => {
      reject()
    }
    script.src = src
    document.getElementsByTagName('body')[0].appendChild(script)
  })
}

export default {
  arrToStr,
  countdown,
  formatMsgTime,
  prefixInteger,
  stringPhone,
  utf16to8,
  objParseParam,
  objParseUrlAndParam,
  getRequestParameters,
  numberFoFixed2,
  loadJs,
}
